package hn.sigit.logic.bpm.actionhandler;

import hn.sigit.dao.hnd.administrative.HND_TransactionDAO;
import hn.sigit.logic.ladmshadow.Util;
import hn.sigit.model.hnd.administrative.HND_ActivityType;
import hn.sigit.model.hnd.administrative.HND_Transaction;

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.def.Event;
import org.jbpm.graph.exe.ExecutionContext;

public class TransactionHandler implements ActionHandler {
	private static final long serialVersionUID = 1L;

	@Override
	public void execute(ExecutionContext executionContext) throws Exception {
		//TODO: Use process key to determine presentation id with executionContext.getProcessInstance().getKey()
		
		long presentationId = Long.parseLong(executionContext.getProcessInstance().getKey());
		HND_Transaction hndTrx = HND_TransactionDAO.loadRequestByPresentationId(presentationId);
		Event event = executionContext.getEvent();
		
		
		if (event.getEventType().equals(Event.EVENTTYPE_NODE_ENTER)) {
			//Update current activity when entering a new node
			String strActivity = executionContext.getNode().getName();
			HND_ActivityType activityType = stringToActivityType(strActivity);
			
			hndTrx.setCurrentActivity(activityType);
			//Update current actor since the task might change its actor when transitioning
			assignCurrentActor(hndTrx, executionContext);
			
			switch (activityType) {
			case ANALYSIS:
				//Always delete the presentation shadow records when entering the Analysis step
				Util.deletePresentationShadow(presentationId, true);
				break;
			case END:
				//End the process when reaching the end state
				executionContext.getProcessInstance().end();
				break;
			}
		}
		else if (event.getEventType().equals(Event.EVENTTYPE_TASK_ASSIGN)) {
			//Update current actor since the task is being assigned
			assignCurrentActor(hndTrx, executionContext);
		}
		
		HND_TransactionDAO.save(hndTrx);
		
		//TODO: Add code for the transaction log
	}
	
	private void assignCurrentActor(HND_Transaction hndTrx, ExecutionContext executionContext) {
		//TODO: more testing with auto assigning actors
		if (executionContext.getTaskInstance() != null) {
			String actor = executionContext.getTaskInstance().getActorId();
			hndTrx.setCurrentActorUserName(actor);
			//TODO: fill the full user name field
		}
		else
			hndTrx.setCurrentActorUserName(null);
	}
	
	private HND_ActivityType stringToActivityType(String strActivity) {
		HND_ActivityType activityType = HND_ActivityType.valueOf(strActivity.toUpperCase());
		return activityType;
	}

}
